package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.Log;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.sso.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 王加鑫
 * @Date 2021/09/01 21:01
 * @Since JDK 1.8
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @RequestMapping("loginVerification")
    @Log
    public ResponseEntity<Object> login(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");
        ErrorResult errorResult = null;
        try {
            String s = userService.login(phone, verificationCode);
            Map<String, Object> result = new HashMap<>();
            String[] ss = StringUtils.split(s,"|");
            if(StringUtils.isNotEmpty(s)){

                if (s.equals("freeze")){
                    errorResult = ErrorResult.builder().errCode("000001").errMessage("该账号被冻结,登录失败").build();
                    return ResponseEntity.status(500).body(errorResult);
                }

                result.put("token",ss[0]);
                result.put("isNew",Boolean.valueOf(ss[1]));
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            log.error("登录失败",e);
        }
        //说明验证码输入错误
        errorResult = ErrorResult.builder().errCode("000001").errMessage("登录失败").build();
        return ResponseEntity.status(500).body(errorResult);
    }


    /**
     * 校验token，根据token查询用户数据
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token")String token) {
        return userService.queryUserByToken(token);

    }
}
